# send_to_last.py
from __future__ import with_statement
import time, sys, httplib, urllib, logging
import simplejson as json
import common

common.setup_logging()

run = True

while run:
    with open('/var/www/readings.json', 'r') as f:
        l = f.read().encode()
    try:
        readings = json.loads(l)
    except:
        logging.debug('json failure: '+"'"+l+"'")
        readings = {u'datetime': ''}

    #print readings

    if readings[u'datetime'] != '':
        params = urllib.urlencode({'content': l})
        conn = httplib.HTTPConnection('roqueislandmonitor.appspot.com')
        headers = {"Content-type": "application/x-www-form-urlencoded",
                   "Accept": "text/plain"}
        conn.request('POST', '/last', params, headers)
        resp = conn.getresponse()
        if resp.status != 200:
            #raise Exception(resp.reason)
            logging.debug('resp.status != 200: '+str(resp.status))
            print resp.status
        resp.read()
        conn.close()

    time.sleep(10)
    # run = False
